﻿using Bussiness;
using CCWin;
using Model;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace Scada
{
    public delegate void ONBindDeviceListHandler();
    public delegate void ONBindDeviceTypeListHandler();
    public delegate void ONBindDevicePOIListHandler(string devTypeCode);
    public partial class Form1 : Skin_Mac
    {
        string _SelDevGuid;
        string _SelDevTypeGuid;
        string _SelDevPOIGuid;
        SynchronizationContext _SynchronizationContext;
        BLL _BLL = new BLL();

        public Form1()
        {
            InitializeComponent();
            tabMain.SelectedIndex = 0;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.chd内容.Width = this.lvw实时采集.Width - this.chd时间.Width - this.chd主题.Width - 20;
            _SynchronizationContext = SynchronizationContext.Current;
            _BLL._UI.ONShowMessage += new ONShowMessageHandler(ShowMessage);
            _BLL._UI.ONUpdateDeviceState += new ONUpdateDeviceStateHandler(UpdateDeviceState);

            cbx设备类型.FieldList = _BLL._DAL.GetDeviceTypeFieldList();
            cbx设备类型.Bind();

            BindDeviceList();
            BindDeviceTypeList();
            BindDevicePOIList(string.Empty);
            ViewConfig();

            _BLL.Start();
        }

        public void ShowMessage(DeviceMessage deviceMessage)
        {
            _SynchronizationContext.Send(ShowMessageCallback, deviceMessage);
        }

        private void ShowMessageCallback(object deviceMessageObj)
        {
            if (lvw实时采集.Items.Count == 1000)
            {
                lvw实时采集.Items.Clear();
            }
            DeviceMessage deviceMessage = (DeviceMessage)deviceMessageObj;
            ListViewItem listViewItem = new ListViewItem();
            listViewItem.SubItems[0].Text = deviceMessage.Time;
            listViewItem.SubItems.Add(deviceMessage.Title);
            listViewItem.SubItems.Add(deviceMessage.Content);
            lvw实时采集.Items.Insert(0, listViewItem);
        }

        public void UpdateDeviceState(Device device)
        {
            _SynchronizationContext.Send(UpdateDeviceStateCallback, device);
        }

        private void UpdateDeviceStateCallback(object deviceObj)
        {
            Device device = (Device)deviceObj;
            foreach(ListViewItem item in lvwDev.Items)
            {
                if (device.DevCode.Equals(item.SubItems[1].Text))
                {
                    if (device.State == 0)
                    {
                        item.ForeColor = Color.Red;
                    }
                    else
                    {
                        item.ForeColor = Color.Green;
                    }

                    item.SubItems[8].Text = device.State == 1 ? "在线" : "离线";
                    item.SubItems[9].Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                }
            }
        }

        private void BindDeviceList()
        {
            List<Device> deviceList = _BLL._DAL.GetDeviceList();
            BindDeviceList(deviceList);
        }

        private void BindDeviceTypeList()
        {
            List<DeviceType> deviceTypeList = _BLL._DAL.GetDeviceTypeList();
            BindDeviceTypeList(deviceTypeList);
        }

        private void BindDevicePOIList(string devTypeGuid)
        {
            if (string.IsNullOrEmpty(devTypeGuid))
            {
                devTypeGuid = cbx设备类型.SelectedValue.ToString();
            }

            List<DevicePOI> devicePOIList = _BLL._DAL.GetDevicePOIList(devTypeGuid);
            BindDevicePOIList(devicePOIList);
        }

        public void BindDeviceList(List<Device> deviceList)
        {
            lvwDev.Items.Clear();
            int index = 1;
            foreach(var device in deviceList)
            {
                ListViewItem listViewItem = new ListViewItem();
                listViewItem.Tag = device.Guid;
                listViewItem.SubItems[0].Text = index.ToString();
                listViewItem.SubItems.Add(device.DevCode);
                listViewItem.SubItems.Add(device.DevName);
                listViewItem.SubItems.Add(device.DevTypeCode);
                listViewItem.SubItems.Add(device.DevTypeName);
                listViewItem.SubItems.Add("3");
                listViewItem.SubItems.Add(device.IP);
                listViewItem.SubItems.Add(device.Port.ToString());
                listViewItem.SubItems.Add(string.Empty);
                listViewItem.SubItems.Add(string.Empty);
                lvwDev.Items.Add(listViewItem);
                index++;
            }
        }

        public void BindDeviceTypeList(List<DeviceType> deviceTypeList)
        {
            lvwDevType.Items.Clear();
            int index = 1;
            foreach (var deviceType in deviceTypeList)
            {
                ListViewItem listViewItem = new ListViewItem();
                listViewItem.Tag = deviceType.Guid;
                listViewItem.SubItems[0].Text = index.ToString();
                listViewItem.SubItems.Add(deviceType.DeviceTypeCode);
                listViewItem.SubItems.Add(deviceType.DeviceTypeName);
                listViewItem.SubItems.Add(deviceType.CaptureFreq.ToString());
                lvwDevType.Items.Add(listViewItem);
                index++;
            }
        }

        public void BindDevicePOIList(List<DevicePOI> devicePOIList)
        {
            lvwDevPOI.Items.Clear();
            int index = 1;
            foreach (var devicePOI in devicePOIList)
            {
                ListViewItem listViewItem = new ListViewItem();
                listViewItem.Tag = devicePOI.Guid;
                listViewItem.SubItems[0].Text = index.ToString();
                listViewItem.SubItems.Add(devicePOI.DevTypeCode);
                listViewItem.SubItems.Add(devicePOI.DevTypeName);
                listViewItem.SubItems.Add(devicePOI.DevPOIName);
                listViewItem.SubItems.Add(devicePOI.DevPOIAlias);
                listViewItem.SubItems.Add(devicePOI.DevPOITypeName);
                listViewItem.SubItems.Add(devicePOI.Address);
                listViewItem.SubItems.Add(devicePOI.Enable.ToString());
                lvwDevPOI.Items.Add(listViewItem);
                index++;
            }
        }

        private void ViewConfig()
        {
            Config config = _BLL._DAL.GetConfig();
            if (config != null)
            {
                txtWebsocketURL.Text = config.WebsocketURL;
                txtLogPath.Text = config.LogPath;
            }
        }

        private void btnDevAdd_Click(object sender, EventArgs e)
        {
            FrmDevAdd frmDevAdd = new FrmDevAdd();
            frmDevAdd.ONBindDeviceList += new ONBindDeviceListHandler(BindDeviceList);
            frmDevAdd.ShowDialog();
        }

        private void btnDevTypeAdd_Click(object sender, EventArgs e)
        {
            FrmDevTypeAdd frmDevTypeAdd = new FrmDevTypeAdd();
            frmDevTypeAdd.ONBindDeviceTypeList += new ONBindDeviceTypeListHandler(BindDeviceTypeList);
            frmDevTypeAdd.ShowDialog();
        }

        private void btnStartORStop_Click(object sender, EventArgs e)
        {
            _BLL.Start();
        }

        private void btnSaveCaptureSetting_Click(object sender, EventArgs e)
        {
            FrmDevPOIAdd frmDevPOIAdd = new FrmDevPOIAdd();
            frmDevPOIAdd.ONBindDevicePOIList += new ONBindDevicePOIListHandler(BindDevicePOIList);
            frmDevPOIAdd.ShowDialog();
        }

        private void btnBrowseDir_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                txtLogPath.Text = dialog.SelectedPath;
            }
        }

        private void btnSaveBaseSetting_Click(object sender, EventArgs e)
        {
            string websocketurl = txtWebsocketURL.Text.Trim();
            string logpath = txtLogPath.Text.Trim();

            if (string.IsNullOrEmpty(websocketurl))
            {
                MessageBox.Show("websocket服务地址空！");
                return;
            }

            if (string.IsNullOrEmpty(logpath))
            {
                MessageBox.Show("日志保存目录空！");
                return;
            }

            if (MessageBox.Show("确认保存吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                Config config = new Config();
                config.WebsocketURL = websocketurl;
                config.LogPath = logpath;
                Result result = _BLL._DAL.SaveConfig(config);
                if (result.Success)
                {
                    MessageBox.Show("保存成功！");
                }
                else
                {
                    MessageBox.Show("保存失败！");
                }
            }
        }

        private void btnEditDev_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_SelDevGuid))
            {
                MessageBox.Show("请选择记录！");
                return;
            }

            FrmDevAdd frmDevAdd = new FrmDevAdd();
            frmDevAdd.ONBindDeviceList += new ONBindDeviceListHandler(BindDeviceList);
            frmDevAdd._DevGuid = _SelDevGuid;
            frmDevAdd.ShowDialog();
        }

        private void btnDelDev_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_SelDevGuid))
            {
                MessageBox.Show("请选择记录！");
                return;
            }

            if (MessageBox.Show("确认删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                Result result=_BLL._DAL.DelDevice(_SelDevGuid);
                if (result.Success)
                {
                    MessageBox.Show("删除成功！");
                    this.BindDeviceList();
                }
                else
                {
                    MessageBox.Show("删除失败！");
                }
            }
        }

        private void btnDelDevType_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_SelDevTypeGuid))
            {
                MessageBox.Show("请选择记录！");
                return;
            }

            if (MessageBox.Show("确认删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                Result result = _BLL._DAL.DelDeviceType(_SelDevTypeGuid);
                if (result.Success)
                {
                    MessageBox.Show("删除成功！");
                    this.BindDeviceTypeList();
                }
                else
                {
                    MessageBox.Show("删除失败！");
                }
            }
        }

        private void btnEditDevType_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_SelDevTypeGuid))
            {
                MessageBox.Show("请选择记录！");
                return;
            }

            FrmDevTypeAdd frmDevTypeAdd = new FrmDevTypeAdd();
            frmDevTypeAdd.ONBindDeviceTypeList += new ONBindDeviceTypeListHandler(BindDeviceTypeList);
            frmDevTypeAdd._DevTypeGuid = _SelDevTypeGuid;
            frmDevTypeAdd.ShowDialog();
        }

        private void lvwDev_MouseClick(object sender, MouseEventArgs e)
        {
            ListViewHitTestInfo info = lvwDev.HitTest(e.X, e.Y);
            if (info.Item != null)
            {
                _SelDevGuid = info.Item.Tag.ToString();
            }
        }

        private void lvwDev_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewHitTestInfo info = lvwDev.HitTest(e.X, e.Y);
            if (info.Item != null)
            {
                FrmDevAdd frmDevAdd = new FrmDevAdd();
                frmDevAdd.ONBindDeviceList += new ONBindDeviceListHandler(BindDeviceList);
                frmDevAdd._DevGuid = info.Item.Tag.ToString();
                frmDevAdd.ShowDialog();
            }
        }

        private void lvwDevType_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewHitTestInfo info = lvwDevType.HitTest(e.X, e.Y);
            if (info.Item != null)
            {
                FrmDevTypeAdd frmDevTypeAdd = new FrmDevTypeAdd();
                frmDevTypeAdd.ONBindDeviceTypeList += new ONBindDeviceTypeListHandler(BindDeviceTypeList);
                frmDevTypeAdd._DevTypeGuid = info.Item.Tag.ToString();
                frmDevTypeAdd.ShowDialog();
            }
        }

        private void lvwDevType_MouseClick(object sender, MouseEventArgs e)
        {
            ListViewHitTestInfo info = lvwDevType.HitTest(e.X, e.Y);
            if (info.Item != null)
            {
                _SelDevTypeGuid = info.Item.Tag.ToString();
            }
        }

        private void btnDelDevPOI_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_SelDevPOIGuid))
            {
                MessageBox.Show("请选择记录！");
                return;
            }

            if (MessageBox.Show("确认删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                Result result = _BLL._DAL.DelDevicePOI(_SelDevPOIGuid);
                if (result.Success)
                {
                    MessageBox.Show("删除成功！");
                    this.BindDevicePOIList(cbx设备类型.SelectedValue.ToString());
                }
                else
                {
                    MessageBox.Show("删除失败！");
                }
            }
        }

        private void btnEditDevPOI_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_SelDevPOIGuid))
            {
                MessageBox.Show("请选择记录！");
                return;
            }

            FrmDevPOIAdd frmDevTypeAdd = new FrmDevPOIAdd();
            frmDevTypeAdd.ONBindDevicePOIList += new ONBindDevicePOIListHandler(BindDevicePOIList);
            frmDevTypeAdd._DevPOIGuid = _SelDevPOIGuid;
            frmDevTypeAdd.ShowDialog();
        }

        private void cbx设备类型_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindDevicePOIList(cbx设备类型.SelectedValue.ToString());
        }

        private void lvwDevPOI_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewHitTestInfo info = lvwDevPOI.HitTest(e.X, e.Y);
            if (info.Item != null)
            {
                FrmDevPOIAdd frmDevTypeAdd = new FrmDevPOIAdd();
                frmDevTypeAdd.ONBindDevicePOIList += new ONBindDevicePOIListHandler(BindDevicePOIList);
                if (info.Item.Tag != null)
                {
                    frmDevTypeAdd._DevPOIGuid = info.Item.Tag.ToString();
                }
                
                frmDevTypeAdd.ShowDialog();
            }
        }

        private void lvwDevPOI_MouseClick(object sender, MouseEventArgs e)
        {
            ListViewHitTestInfo info = lvwDevPOI.HitTest(e.X, e.Y);
            if (info.Item != null)
            {
                if (info.Item.Tag != null)
                {
                    _SelDevPOIGuid = info.Item.Tag.ToString();
                }
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.WindowState = FormWindowState.Minimized;
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (WindowState == FormWindowState.Minimized)
                {
                    //最大化时任务栏不会遮罩主界面
                    this.MaximumSize = new Size(Screen.PrimaryScreen.WorkingArea.Width + 15, Screen.PrimaryScreen.WorkingArea.Height + 15);
                    ShowMainFrm();
                }
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                ShowMainFrm();
            }
        }

        /// <summary>
        /// 显示主界面
        /// </summary>
        private void ShowMainFrm()
        {
            //还原窗体显示
            this.WindowState = FormWindowState.Maximized;
            //激活窗体并给予它焦点
            this.Activate();
            //任务栏区显示图标
            this.ShowInTaskbar = true;
        }

        private void 主界面ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.ShowMainFrm();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确认退出程序？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                // 关闭所有的线程
                this.Dispose();
                this.Close();
                System.Environment.Exit(0);
            }
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            //判断是否选择的是最小化按钮
            if (WindowState == FormWindowState.Minimized)
            {
                //隐藏任务栏区图标
                this.ShowInTaskbar = false;
                //图标显示在托盘区
                this.notifyIcon1.Visible = true;
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://fanyeyong.com?from=scada");
        }
    }
}
